const jwt = require("jsonwebtoken");

module.exports = (options, app) => {
  return async (ctx, next) => {
    const token = ctx.request.headers.token;
    if (!token) {
      ctx.send({ success: false, code: 401, msg: "未登录，无访问权限" });
    } else {
      try {
        const data = jwt.verify(token, ctx.app.config.jwt.secret);
        console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",data);
        ctx.auth = {
          _id: data.id,
        };
      } catch (error) {
        if (error.name == "TokenExpiredError") {
          return ctx.send({
            success: false,
            code: 401,
            msg: "登录过期，请重新登陆",
          });
        } else {
          ctx.send({ success: false, code: 401, msg: "未登录，无访问权限" });
        }
      }

      await next();
    }
  };
};
